package com.ping.common;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

public abstract class MyHttpClient {
	private static String host = "localhost";
	private static int port = 8080;
	private static String protocol = "http";
	private static String UTF8 = "utf-8";
	
	private HttpClient client;
	
	public MyHttpClient() {
		this.client = new HttpClient();
		this.client.getHostConfiguration().setHost(host, port, protocol);
		
	}
	
	public String get(String url){
		HttpMethod get = new GetMethod(url);
		get.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, UTF8);
		try {
			this.client.executeMethod(get);
			String content = getResponseBody(get);
			get.releaseConnection();
			return content;
		} catch (HttpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}
	
	public String post(String url, NameValuePair[] params){
		HttpMethod post = new PostMethod(url);
		post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, UTF8);
		post.setQueryString(params);
		
		try {
			this.client.executeMethod(post);
			String content = getResponseBody(post);
			post.releaseConnection();
			return content;
		} catch (HttpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}
	
	public String getResponseBody(HttpMethod method){
		StringBuffer content = new StringBuffer();
		BufferedReader br;

		try {
			InputStreamReader stream = new InputStreamReader(method.getResponseBodyAsStream(), UTF8);
			br = new BufferedReader(stream);
			
			String line;
			while((line = br.readLine())!=null){
				content.append(line);
			}
			
			stream.close();
			br.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return content.toString();
	}
	
	public abstract Object loadData(String result);
}
